package com.canyou.utils;

import com.canyou.constants.CommonConstants;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Pattern;

/**
 * url: encode/decode
 *
 * @author fy
 * @date 20/04/22 9:30
 */
public final class UrlUtils {

    private UrlUtils() {
    }

    /**
     * 匹配字符串为url的正则表达式
     */
    public static final String URL_PATTERN = "((http|ftp|https)://)(([a-zA-Z0-9\\._-]+\\.[a-zA-Z]{2,6})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\\&%_\\./-~-]*)?";

    /**
     * 对url进行utf-8编码
     *
     * @param url
     * @return
     */
    public static String encode(String url) {
        String newUrl;
        try {
            newUrl = URLEncoder.encode(url, CommonConstants.DEFAULT_ENCODING);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        return newUrl;
    }

    /**
     * 对编码的url进行解码
     *
     * @param url
     * @return
     */
    public static String decode(String url) {
        String newUrl;
        try {
            newUrl = URLDecoder.decode(url, CommonConstants.DEFAULT_ENCODING);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        return newUrl;
    }

    /**
     * 匹配一个字符串是否为url
     *
     * @param url
     * @return
     */
    public static boolean isUrl(String url) {
        boolean isMatch = Pattern.matches(URL_PATTERN, url);
        return isMatch;
    }

    /**
     * 获取一个链接的主机地址
     *
     * @param url
     * @return
     */
    public static String getHost(String url) {
        URL tempUrl;
        try {
            tempUrl = new URL(url);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
        return tempUrl.getHost();
    }

    /**
     * 组装queryString的字段
     *
     * @param params
     * @param urlEncoder
     * @return
     */
    public static String packageQuery(Map<String, String> params, boolean urlEncoder) {
        // 先将参数以其参数名的字典序升序进行排序
        TreeMap<String, String> sortedParams = new TreeMap<>(params);
        // 遍历排序后的字典，将所有参数按"key=value"格式拼接在一起
        StringBuilder sb = new StringBuilder();
        boolean first = true;
        for (Map.Entry<String, String> param : sortedParams.entrySet()) {
            String value = param.getValue();
            if (StringUtils.isBlank(value)) {
                continue;
            }
            if (first) {
                first = false;
            } else {
                sb.append("&");
            }
            sb.append(param.getKey()).append("=");
            if (urlEncoder) {
                value = encode(value);
            }
            sb.append(value);
        }
        return sb.toString();
    }

    /**
     * 将url和queryString拼接起来
     *
     * @param url
     * @param queryStr
     * @return
     */
    public static String concatQuery(String url, String queryStr) {
        if (StringUtils.isBlank(url)) {
            throw new RuntimeException("url不能为空");
        }
        String concatStr = "?";
        String joinStr = "&";
        if (url.lastIndexOf(concatStr) > 0) {
            return url + joinStr + queryStr;
        } else {
            return url + concatStr + queryStr;
        }
    }

}
